//导入进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './utils/auth'
import { useStore } from './store/user'
import { useMenuStore } from './store/menu'
import router, { asyncRoutes } from './router'
import { getPageTitle } from '@/utils/getPageTitle'
//配置进度条
// 显示右上角螺旋加载提示

Nprogress.configure({ showSpinner: false })
//白名单
const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  // console.log('从哪里来',from)
  // console.log('到哪里去',to)
  //console.log('标题',to.meta.title)
  //进度条开始时
  Nprogress.start()
  const token = getToken()
  document.title = getPageTitle(to.meta.title as string)

  if (!token) {
    if (whiteList.includes(to.path)) return next()
    next('/login')
    //进度条结束
    Nprogress.done()
  }
  if (to.path === '/login') {
    next('/')
    //进度条结束
    Nprogress.done()
    return
  }
  const store = useStore()
  if (!store.userId) {
    const menus = await store.loadProfile()
    // console.log('menus', menus)
    // console.log('asyncRoutes', asyncRoutes)
    const doRoutes = asyncRoutes.filter((item) => menus.includes(item.children![0].name))
    console.log('doRoutes', doRoutes)
    doRoutes.forEach((item) => router.addRoute(item))
    const menuStore = useMenuStore()
    menuStore.setMenuList(doRoutes)
    // 解决刷新出现的白屏bug
    // 如果 addRoute 并未完成，路由守卫会一层一层的执行执行，直到 addRoute 完成，找到对应的路由
    //return next({ ...to, replace: true })
    return next({
      path: `${ to.path }`,
    })
  }
  next()
})
router.afterEach(() => {
  //进度条结束
  Nprogress.done()
})
